//
//  VK_Picker.m
//  HealthyLife
//
//  Created by Vescky on 12-12-17.
//  Copyright (c) 2012年 Vescky. All rights reserved.
//

#import "VK_Picker.h"
#import "DateUtility.h"
#import <QuartzCore/QuartzCore.h>

#define PickerDataLength 10000

@interface VK_Picker ()

@end

@implementation VK_Picker
@synthesize labelTop;
@synthesize pickerType;
@synthesize pickerVK;
@synthesize buttonLeft,buttonRight;
@synthesize delegate;
@synthesize pickerViewData;
@synthesize selectedIndex,selectedComponent;
@synthesize componentOfPicker;
@synthesize dateTime;
@synthesize cycleData;
@synthesize selectDate;
@synthesize bgImage;
@synthesize banLayerLayout;
@synthesize maxDate,minDate;

#pragma mark - Private
- (void)initView {
    for (int i = 0; i < [pickerViewData count]; i++) {
        NSArray *arr = [pickerViewData objectAtIndex:i];
        if (i < [cycleData count] && [[cycleData objectAtIndex:i] isEqualToString:@"0"] ) {
            [pickerVK selectRow:0 inComponent:i animated:NO];
        }
        else {
           int arrCount = [arr count];
            int _selected = (PickerDataLength/2 - (PickerDataLength/2)%arrCount);
            [pickerVK selectRow:_selected inComponent:i animated:NO];
        }
        
    }
    
    if (bgImage) {
        [bgImageView setImage:bgImage];
    }
    
    if (!banLayerLayout) {
        self.view.layer.cornerRadius = 5.0;
        self.view.layer.borderWidth = 2.0;
    }
    
   
}

- (void)initData {
    if (!selectDate) {
        selectDate = [NSDate date];
    }
}

- (void)changeLabel {
    if ([delegate respondsToSelector:@selector(VK_labelShowEvent)]) {
        [delegate VK_labelShowEvent];
    }
    else {
        switch (pickerType) {
            case TimePickerHH_mm:
                [labelTop setText:getStringFromDate(@"HH:mm", selectDate)];
                break;
            case TimePickerHH_mm_ss:
                [labelTop setText:getStringFromDate(@"HH:mm:ss", selectDate)];
                break;
            case DatePickeryyyy_MM_dd:
                [labelTop setText:getStringFromDate(@"yyyy-MM-dd", selectDate)];
                break;
                
            default:
                break;
        }
    }
}

- (void)setMaxAndMinDate {
    if (!maxDate && !minDay) {
        return;
    }
    
    isLimitDate = YES;
    
    if (maxDate) {
       NSString *maxDateStr = getStringFromDate(@"yyyy-MM-dd", maxDate);
        NSArray *maxArr = [maxDateStr componentsSeparatedByString:@"-"];
        if ([maxArr count] < 3) {
            return;
        }
        maxYear = [[maxArr objectAtIndex:0] intValue];
        maxMonth = [[maxArr objectAtIndex:1] intValue];
        maxDay = [[maxArr objectAtIndex:2] intValue];
    }
    
    
    if (minDate) {
        NSString *minDateStr = getStringFromDate(@"yyyy-MM-dd", minDate);
        NSArray *minArr = [minDateStr componentsSeparatedByString:@"-"];
        if ([minArr count] < 3) {
            return;
        }
        minYear = [[minArr objectAtIndex:0] intValue];
        minMonth = [[minArr objectAtIndex:1] intValue];
        minDay = [[minArr objectAtIndex:2] intValue];
    }
    
    NSArray *yArray = [self getTimerFormatArrayFromNumber:minYear?minYear:1970 ToNumber:maxYear?maxYear:3000];
    [pickerViewData setObject:yArray atIndexedSubscript:0];
    [pickerVK reloadComponent:0];
    
}

#pragma mark - Default Picker Type
- (NSMutableArray*)getTimerFormatArrayFromNumber:(int)_fromNumber ToNumber:(int)_toNumber  {
    NSMutableArray *_array = [[NSMutableArray alloc] init];
    for (int i = _fromNumber; i <= _toNumber; i++) {
        if (i <= 9) {
            [_array addObject:[NSString stringWithFormat:@"0%d",i]];
        }
        else {
            [_array addObject:[NSString stringWithFormat:@"%d",i]];
        }
    }
    return _array;
}

- (void)makeHHmmPicker {
    NSMutableArray *arrHH = [self getTimerFormatArrayFromNumber:0 ToNumber:23];
    NSMutableArray *arrMM = [self getTimerFormatArrayFromNumber:0 ToNumber:59];
    
    if (!pickerViewData) {
        pickerViewData = [[NSMutableArray alloc] init];
    }
    [pickerViewData removeAllObjects];
    
    [pickerViewData addObject:arrHH];
    [pickerViewData addObject:arrMM];
    
    
    if (!cycleData) {
        cycleData = [[NSMutableArray alloc] init];
    }
    [cycleData removeAllObjects];
    
    [cycleData addObject:[NSString stringWithFormat:@"1"]];
    [cycleData addObject:[NSString stringWithFormat:@"1"]];
}

- (void)makeHHmmssPicker {
    NSMutableArray *arrHH = [self getTimerFormatArrayFromNumber:0 ToNumber:23];
    NSMutableArray *arrMM = [self getTimerFormatArrayFromNumber:0 ToNumber:59];
    NSMutableArray *arrSS = [self getTimerFormatArrayFromNumber:0 ToNumber:59];
    
    if (!pickerViewData) {
        pickerViewData = [[NSMutableArray alloc] init];
    }
    
    [pickerViewData removeAllObjects];
    
    [pickerViewData addObject:arrHH];
    [pickerViewData addObject:arrMM];
    [pickerViewData addObject:arrSS];
    
    if (!cycleData) {
        cycleData = [[NSMutableArray alloc] init];
    }
    [cycleData removeAllObjects];
    
    [cycleData addObject:[NSString stringWithFormat:@"1"]];
    [cycleData addObject:[NSString stringWithFormat:@"1"]];
    [cycleData addObject:[NSString stringWithFormat:@"1"]];
}

- (void)makeyyyyMMddPicker {
    NSMutableArray *arrYYYY = [self getTimerFormatArrayFromNumber:1970 ToNumber:3000];
    NSMutableArray *arrMM = [self getTimerFormatArrayFromNumber:1 ToNumber:12];
    dayForPicker = [self getTimerFormatArrayFromNumber:1 ToNumber:31];
    
    if (!pickerViewData) {
        pickerViewData = [[NSMutableArray alloc] init];
    }

    [pickerViewData removeAllObjects];

    [pickerViewData addObject:arrYYYY];
    [pickerViewData addObject:arrMM];
    [pickerViewData addObject:dayForPicker];
    
    if (!cycleData) {
        cycleData = [[NSMutableArray alloc] init];
    }
    [cycleData removeAllObjects];
    
    [cycleData addObject:[NSString stringWithFormat:@"0"]];
    [cycleData addObject:[NSString stringWithFormat:@"1"]];
    [cycleData addObject:[NSString stringWithFormat:@"1"]];
}

- (int)getDayCountOfMonth:(int)_month Year:(int)_year {
    int _dayCount = 0;
    if (_month == 2) {
        if (_year % 4 == 0) {
            _dayCount = 28;
        }
        else if (_year % 100 == 0) {
            _dayCount = 29;
        }
        else if (_year % 400 == 0) {
            _dayCount = 28;
        }
        else {
            _dayCount = 29;
        }
    }
    else if (_month == 4 || _month == 6 || _month == 9 || _month == 11 ) {
        _dayCount = 30;
    }
    else {
        _dayCount = 31;
    }
    return _dayCount;
}

- (void)changeDayArrayWithDate:(NSDate*)_date {
    if (!_date) {
        return;
    }
    NSString *dateStr = getStringFromDate(@"yyyy-MM-dd", _date);
    NSArray *arrDate = [dateStr componentsSeparatedByString:@"-"];
    
    if ([pickerViewData count] < 3 || pickerType != DatePickeryyyy_MM_dd) {
        return;
    }
    int _dayCount = [self getDayCountOfMonth:[[arrDate objectAtIndex:1] intValue] Year:[[arrDate objectAtIndex:0] intValue]];
    NSMutableArray *_arr = [pickerViewData objectAtIndex:2];
    _arr = [self getTimerFormatArrayFromNumber:1 ToNumber:_dayCount];
    [pickerViewData setObject:_arr atIndexedSubscript:2];
    [pickerVK reloadComponent:2];
    [self setDateTime:_date animated:NO];
}

#pragma mark - Private 映射数组值
//数组中寻找对应的内容
- (int)searchIndexForKey:(NSString*)_key  InArray:(NSArray*)_array {
    for (int i = 0; i < [_array count]; i++) {
        if ([_key isEqualToString:[_array objectAtIndex:i]]) {
            return i;
        }
    }
    return 0;
}

- (int)searchRowForDataSourceIndex:(int)_index inComponent:(int)_component {
    int _arrayCount = [[pickerViewData objectAtIndex:_component] count];
    int _currentIndex = [pickerVK selectedRowInComponent:_component];
    
    int _gap = _currentIndex % _arrayCount;
    
    int zeroPoint = _currentIndex - _gap;//起始位置
    
    _currentIndex = zeroPoint + _index;
    
    return _currentIndex;
}

- (void)setDateTime:(NSDate*)_date animated:(BOOL)animated {
    if (!_date) {
        return;
    }
    NSString *dateStr;
    NSArray *arr;
    if (pickerType == TimePickerHH_mm) {
        dateStr = getStringFromDate(@"HH:mm", _date);
        arr = [dateStr componentsSeparatedByString:@":"];
    }
    else if(pickerType == TimePickerHH_mm_ss) {
        dateStr = getStringFromDate(@"HH:mm:ss", _date);
        arr = [dateStr componentsSeparatedByString:@":"];
    }
    else if(pickerType == DatePickeryyyy_MM_dd) {
        dateStr = getStringFromDate(@"yyyy-MM-dd", _date);
         arr = [dateStr componentsSeparatedByString:@"-"];
    }
    
    for (int i = 0; i < [arr count]; i++) {
        [self setSelectedRowWithContents:[arr objectAtIndex:i] inComponents:i animated:animated];
    }
    
    selectDate = [self getSeletedDateTime];
    
}

#pragma mark - Public
- (void)initWithType:(int)_type {
    [self createPicker:_type];
}

- (void)createPicker:(int)_pickerType {
    
    pickerType = _pickerType;
    
    switch (_pickerType) {
        case TimePickerHH_mm:
            [self makeHHmmPicker];
            break;
        case TimePickerHH_mm_ss:
            [self makeHHmmssPicker];
            break;
        case DatePickeryyyy_MM_dd:
            [self makeyyyyMMddPicker];
            break;
            
        default:
            break;
    }
    
    if ([pickerViewData count]) {
        componentOfPicker = [pickerViewData count];
    }
    else {
        componentOfPicker = 1;
    }
    
}

- (void)setSelectedRowWithContents:(NSString*)_contents inComponents:(int)_component animated:(bool)_animated {
    
    int _selected = [self searchIndexForKey:_contents InArray:[pickerViewData objectAtIndex:_component]];
    
    _selected = [self searchRowForDataSourceIndex:_selected inComponent:_component];
    
    [pickerVK selectRow:_selected inComponent:_component animated:_animated];
}


- (void)setSelectRow:(int)_row inComponent:(NSInteger)_component animated:(BOOL)animated {
    _row = [self searchRowForDataSourceIndex:_row inComponent:_component];
    [pickerVK selectRow:_row inComponent:_component animated:animated];
}

- (void)initDate:(NSDate*)_date withAnimate:(bool)_animate {
    dateTime = _date;
    setDateAnimate = _animate;
}

- (NSDate*)getSeletedDateTime {
    NSDate *_date;
    if (pickerType > Custom && pickerType <= DatePickeryyyy_MM_dd) {
        
        NSArray *arr1 = [pickerViewData objectAtIndex:0];
        NSString *_Datestr = [arr1 objectAtIndex:([pickerVK selectedRowInComponent:0] % [arr1 count])];
        
        for (int i = 1; i < [pickerViewData count]; i++) {
            NSArray *_arr = [pickerViewData objectAtIndex:i];
            int _s = [pickerVK selectedRowInComponent:i] % [_arr count];
            NSString *str = [_arr objectAtIndex:_s];
            if (pickerType == DatePickeryyyy_MM_dd) {
                _Datestr = [_Datestr stringByAppendingFormat:@"-%@",str];
            }
            else {
                _Datestr = [_Datestr stringByAppendingFormat:@":%@",str];
            }
        }
        
        if (pickerType == TimePickerHH_mm) {
            _date = getDateFromString(@"HH:mm", _Datestr);
        }
        else if (pickerType == TimePickerHH_mm_ss) {
            _date = getDateFromString(@"HH:mm:ss", _Datestr);
        }
        else if (pickerType == DatePickeryyyy_MM_dd) {
            _date = getDateFromString(@"yyyy-MM-dd", _Datestr);
        }
        
    }
    return _date;
}

#pragma mark - Button action
- (IBAction)btnLeftAction:(id)sender {
    if ([delegate respondsToSelector:@selector(VK_PickerLeftButtonEvent)]) {
        [delegate VK_PickerLeftButtonEvent];
    }
}

- (IBAction)btnRightAction:(id)sender {
    if ([delegate respondsToSelector:@selector(VK_PickerLeftButtonEvent)]) {
        [delegate VK_PickerRightButtonEvent];
    }
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView  {
    return [pickerViewData count];
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

    if (cycleData && [[cycleData objectAtIndex:component] isEqualToString:@"0"]) {
        return [[pickerViewData objectAtIndex:component] count];
    }
    
    return PickerDataLength;//循环显示
}

#pragma mark - UIPickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    selectedComponent = component;
    selectedIndex = row % [[pickerViewData objectAtIndex:component] count];
    
    if (component < 2 && pickerType == DatePickeryyyy_MM_dd) {
        //reload day总数
        int _yearRowCount = [[pickerViewData objectAtIndex:0] count];
        int _monthRowCount = [[pickerViewData objectAtIndex:1] count];
        int _dayRowCount = [[pickerViewData objectAtIndex:2] count];
        NSString* _year = [[pickerViewData objectAtIndex:0] objectAtIndex:[pickerVK selectedRowInComponent:0]%_yearRowCount] ;
        NSString* _month = [[pickerViewData objectAtIndex:1] objectAtIndex:[pickerVK selectedRowInComponent:1]%_monthRowCount] ;
        NSString* _day = [[pickerViewData objectAtIndex:2] objectAtIndex:[pickerVK selectedRowInComponent:2]%_dayRowCount] ;
        NSDate *_date = getDateFromString(@"yyyy-MM-dd", [NSString stringWithFormat:@"%@-%@-%@",_year,_month,_day]);
        [self changeDayArrayWithDate:_date];
    }
    
    selectDate = [self getSeletedDateTime];
    [self changeLabel];
}

/*
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString *str = @" ";
    if (component < [pickerViewData count]) {
        NSArray *arr = [pickerViewData objectAtIndex:component];
        
        int _row = row % [arr count];
        
        str = [arr objectAtIndex:_row];
        
    }
    return str;
}
*/
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    NSString *str = @" ";
    if (component < [pickerViewData count]) {
        NSArray *arr = [pickerViewData objectAtIndex:component];
        
        int _row = row % [arr count];
        
        str = [arr objectAtIndex:_row];
        
    }
    
    UILabel *retval = (id)view;
    if (!retval) {
        retval= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
    }
    retval.textAlignment = 1;
    [retval setText:str];
    
    return retval;
}


#pragma mark - lifeCycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }  
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initData];
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setDateTime:dateTime animated:setDateAnimate];//设置
    //selectDate = [self getSeletedDateTime];
    [self changeLabel];
    if (pickerType) {
        [self setMaxAndMinDate];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
